//
//  HomeScreenWidgetsAppIntent.swift
//  DashBoard
//
//  Created by 王麒皓 on 2023/7/19.
//

import AppIntents
import WidgetKit
import ActivityKit

struct SignInWidget: AppIntent {
    static var title: LocalizedStringResource = "签到"
    
    func perform() async throws -> some IntentResult {
        var allClasses: [EventWithClassName] = []
        let classData = ClassNameData()
        let date = Date()
        classData.IS_INTERNET_OPERATION_ALLOWED_FLAG = true
        _ = await classData.downloadDataByHttp()
        for _class in classData.ClassName {
            let classroom = CoreData(classNameStr: _class.name)
            classroom.IS_INTERNET_OPERATION_ALLOWED_FLAG = true
            _ = await classroom.downloadDataByHttp()
            for _event in classroom.events {
                if _event.techer == UserDefaults(suiteName: "group.classmanager")!.string(forKey: "teacherName") && _event.state == -1 {
                    allClasses.append(EventWithClassName(_event: _event, name: _class.name, classType: classroom.classes[_event._class].name))
                }
            }
        }
        if allClasses.count != 0 {
            let sortedClass = allClasses.sorted(by: {return $0._event.start < $1._event.start})
            var _class: EventWithClassName? = nil
            for __class in sortedClass {
                let remaining = Int((__class._event.start-date.timeIntervalSince1970)/60)
                if remaining >= 0 {
                    _class = __class
                    break
                }
            }
            if let _class = _class {
                let classroom = CoreData(classNameStr: _class.name)
                classroom.IS_INTERNET_OPERATION_ALLOWED_FLAG = true
                _ = await classroom.downloadDataByHttp()
                for idx in 0..<classroom.events.count {
                    if classroom.events[idx].start == _class._event.start {
                        var BLEName: String? = nil
                        for j in 0..<classData.ClassName.count {
                            if classData.ClassName[j].name == _class.name {
                                BLEName = classData.ClassName[j].BLEName
                                break
                            }
                        }
                        if let BLEName = BLEName {
                            let signTool = BLESignTool(classBLEName: BLEName, classData: classroom, eventIndex: idx)
                            let result = await signTool.check()
                                && abs(Date().timeIntervalSince1970 - _class._event.start)/60 <= 5
                            if !result {
                                WidgetCenter.shared.reloadAllTimelines()
                                return .result()
                            }
                            
                            //MARK: Request a Live Activity
                            let initialContentState = HomeScreenWidgetsAttributes.ContentState(remainingMinute: Date(timeIntervalSince1970: _class._event.start)...Date(timeIntervalSince1970: _class._event.end))
                            let activityAttributes = HomeScreenWidgetsAttributes(totalMinute: Int((_class._event.end-_class._event.start)/60), classTypeString: classroom.classes[_class._event._class].name, classString: _class.name)
                            do {
                                if #available(iOS 16.1, *) {
                                    let activity = try Activity.request(attributes: activityAttributes, content: ActivityContent(state: initialContentState, staleDate: nil))
                                    Task {
                                        await activity.end(ActivityContent(state: initialContentState, staleDate: nil), dismissalPolicy: .after(Date(timeIntervalSince1970: _class._event.end)))
                                    }
                                } else {
                                    // Fallback on earlier versions
                                }
                                print("Requested a Live Activity.")
                            } catch (let error) {
                                print("Error requesting a Live Activity \(error.localizedDescription).")
                            }
                            
                            classroom.events[idx].state = 0
                            _ = await classroom.uploadDataByHttp()
                        }
                        break
                    }
                }
            }
        }
        WidgetCenter.shared.reloadAllTimelines()
        return .result()
    }
}
